﻿using ebMS3dotnet.Core.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ebMS3dotnet.Core
{
    class ebMS3ContextPModeMapper
    {
        internal void PopulateContextFromPModeForUserMessage(ebMS3Context context, PMode pMode)
        {
            if (context.UserMessage == null)
                context.UserMessage = new UserMessageInfo();

            if (pMode.BusinessInfo != null && string.IsNullOrWhiteSpace(context.UserMessage.Mpc))
            {
                context.UserMessage.Mpc = pMode.BusinessInfo.Mpc;
            }

            context.UserMessage.MessageInfo.MessageID = Guid.NewGuid().ToString();
            context.UserMessage.MessageInfo.Timestamp = DateTime.Now.ToUniversalTime();
            context.UserMessage.CollaborationInfo.ConversationID = Guid.NewGuid().ToString();

            if (pMode.Initiator != null)
                context.UserMessage.PartyInfo.From.Add(new Party() { PartyId = pMode.Initiator.Party, Role = pMode.Initiator.Role });

            if (pMode.Responder != null)
            {
                if (string.IsNullOrWhiteSpace(context.UserMessage.PartyInfo.To.PartyId))
                    context.UserMessage.PartyInfo.To.PartyId = pMode.Responder.Party;

                if (string.IsNullOrWhiteSpace(context.UserMessage.PartyInfo.To.Role))
                    context.UserMessage.PartyInfo.To.Role = pMode.Responder.Role;
            }

            if (!string.IsNullOrWhiteSpace(pMode.ID))
            {
                    context.UserMessage.CollaborationInfo.AgreementRef.PMode = pMode.ID;
            }

            if (pMode.BusinessInfo != null)
            {
                if (string.IsNullOrWhiteSpace(context.UserMessage.CollaborationInfo.Service.Value))
                    context.UserMessage.CollaborationInfo.Service.Value = pMode.BusinessInfo.Service;

                if (string.IsNullOrWhiteSpace(context.UserMessage.CollaborationInfo.Action))
                    context.UserMessage.CollaborationInfo.Action = pMode.BusinessInfo.Action;
            }

        }
    }
}
